'''
Created on 13/gen/2010

@author: syn
'''

from elixir import session
from ui.GladeBase import GladeBase
from utils.Environment import logger
from utils import string_hook
from data.models import Edition
from ui import mandatory_data_error, get_warning_dialog
from sqlalchemy.exc import IntegrityError
import gtk

NO_ENTITY = -1

class AddEdition(GladeBase):
    def __init__(self):
        logger.debug("UI: %s instance created" % self.__class__)
        GladeBase.__init__(self, 'add_genre_dialog')
        self._init_gui_components()
        
        self.root_component.set_title("Add Edition")
        self.entity_key = NO_ENTITY
    
    def _init_gui_components(self):
        """
        Intialize gui components as needed. This is useful in the contructor or 
        binded with particular actions (for instance, a "clear" button, or "new" button) 
        """
        pass
    
    def _retrieve_components(self):
        """
        Retrieve all used gui components from builder. This method is called in the
        GladeBase constructor
        """
        self.get_from_builder('name_entry')
        self.get_from_builder('description_textbuffer')
    
    def _has_valid_data(self):
        """
        Formal control for data in the input form.
        @return: boolean. 'True' when data is valid
        """
        name = self.name_entry.get_text()
        
        if not name:
            mandatory_data_error("Name", self.name_entry)
            return False
        
        return True
    
    def _save_data(self):
        """
        Save changes to db. 
        @return: 'True' if data have been successfully saved 
        """
        if not self._has_valid_data():
            return False
        
        # manage Genre data object
        if self.entity_key == NO_ENTITY:
            edition = Edition()
        else:
            edition = Edition.get_by(id=self.entity_key)
        
        edition.name = self.name_entry.get_text()
        (start,end) = self.description_textbuffer.get_bounds()
        edition.description = string_hook(self.description_textbuffer.get_text(start,end).strip())
        
        try:
            session.commit()
        except IntegrityError, e:
            logger.debug(" Errore db: %s" % e)
            get_warning_dialog(None, "This edition already exists")
            session.rollback()
            return False
        
        self.entity_key = edition.id
        return True
    
    # Signals
    def on_ok_button_clicked(self, object, data=None):
        if self._save_data():
            self.root_component.response(gtk.RESPONSE_OK)
    
    def run(self):
        return self.root_component.run()
    